// @flow
import React from 'react'
import styles from './CustomerFillter.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Input, Row, Col, Button, Select } from 'antd'
import { connect } from 'react-redux'

const Option = Select.Option

type Props = {
  userId: string,
  getData: Function
}

type State = {
  eventName: string,
  keyName: string,
  eventType: Array<Object>,
  customer: Array<Object>,
  devices: Array<Object>
}

class Fillter extends React.Component {
  props: Props
  state: State
  searchQuery: string
  searchInfo: Object
  handleEventName: Function
  handleKeyName: Function
  handleSearch: Function
  handleEventType: Function
  handleCustomer: Function
  handleDevice: Function
  getCustomerDeviceData: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      eventType: [{ value: '', label: '全部' }],
      eventName: '',
      keyName: '',
      customer: [{ id: '', name: '全部' }],
      devices: [{ id: '', name: '全部' }]
    }
    this.handleEventName = this.handleEventName.bind(this)
    // this.handleKeyName = this.handleKeyName.bind(this)
    // this.handleEventType = this.handleEventType.bind(this)
    this.handleCustomer = this.handleCustomer.bind(this)
    // this.handleDevice = this.handleDevice.bind(this)
    // this.getCustomerDeviceData = this.getCustomerDeviceData.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.searchInfo = {}
  }

  componentDidMount () {
    // this.getFillterDatas(`${__SERVICE_API__}sys/dicts?type=eventType`, 'eventType')
    this.getFillterDatas(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`, 'customer')
    // this.getFillterDatas(`${__SERVICE_API__}device/devices?pageSize=200000`, 'devices')
  }
  getFillterDatas (url: string, name: string) {
    universalFetch(url)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      let data = this.state[name]
      data.push(...json.result)
      this.setState({ [name]: data })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  handleSearch () {
    let { eventName, keyName, eventType, customer, device } = this.searchInfo
    //  不确定是否有值,没有则设置为空
    eventName = eventName || ''
    // keyName = keyName || ''
    // eventType = eventType || ''
    customer = customer || ''
    // device = device || ''
    // let searchQuery = `&keyName=${keyName}&deviceId=${device}&customerId=${customer}&name=${eventName}&type=${eventType}`
    let searchQuery = `&customerId=${customer}&name=${eventName}`
    this.props.getData(searchQuery)
  }
  handleEventName (e: any) {
    this.searchInfo.eventName = e.target.value
  }
  // handleKeyName (e: any) {
  //   this.searchInfo.keyName = e.target.value
  // }
  // handleEventType (value: any) {
  //   if (value === '全部') {
  //     this.searchInfo.eventType = ''
  //     return
  //   }
  //   this.searchInfo.eventType = value
  // }
  handleCustomer (value: any) {
    // console.log(value);
    if (value === '全部') {
      this.searchInfo.customer = ''
      this.getCustomerDeviceData('', 'devices')
      return
    }
    this.searchInfo.customer = String(value)
    this.getCustomerDeviceData(value, 'devices')
  }
  // getCustomerDeviceData (val: any, name: string) {
  //   let url = ''
  //   if (val === '' || val == null) {
  //     url = `${__SERVICE_API__}device/devices`
  //   } else {
  //     url = `${__SERVICE_API__}device/customers/${val}/devices`
  //   }
  //   universalFetch(url)
  //     .then(res => res.json())
  //     .then((json) => {
  //       if (json.code !== 200000) {
  //         throw new Error(JSON.stringify({ code: json.code, message: json.message }))
  //       }
  //       let data = [{ id: '', name: '全部' }]
  //       data.push(...json.result)
  //       this.setState({ [name]: data })
  //     })
  //     .catch((error) => {
  //       handleFetchError(error)
  //       console.error(error)
  //     })
  // }
  // handleDevice (value: any) {
  //   // console.log(value);
  //   if (value === '全部') {
  //     this.searchInfo.device = ''
  //     return
  //   }
  //   this.searchInfo.device = String(value)
  // }
  render () {
    const { eventType, customer, devices } = this.state
    return (
      <div className={styles['searchBox']}>
        <Row gutter={24} justify='center'>
          <Col className={styles['ant-col-3']} span={3}>
            <div className='gutter-box'>
              <Input placeholder='名称' onInput={this.handleEventName} onPressEnter={this.handleSearch} />
            </div>
          </Col>
          {/* <Col className={styles['ant-col-2']} span={2}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='事件类型'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleEventType}
             >
                {eventType.map((item, index) => {
                  return <Option value={item.value} key={index} className={styles['optionBox']}>{item.label}</Option>
                })}
              </Select>
            </div>
          </Col> */}
          <Col className={styles['ant-col-3']} span={2}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='客户'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleCustomer}
             >
                {customer.map((item, index) => {
                  return <Option value={item.id} key={index} className={styles['optionBox']}>{item.name}</Option>
                })}
              </Select>
            </div>
          </Col>
          {/* <Col className={styles['ant-col-2']} span={2}>
            <div className='gutter-box'>
              <Select
                showSearch
                placeholder='设备'
                optionFilterProp='children'
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                className={styles['selctBox']}
                onSelect={this.handleDevice}
             >
                {devices.map((item, index) => {
                  return <Option value={item.id} key={index} className={styles['optionBox']}>{item.name}</Option>
                })}
              </Select>
            </div>
          </Col> */}
          {/* <Col className={styles['ant-col-2']} span={3}>
            <div className='gutter-box'>
              <Input placeholder='关键字' onInput={this.handleKeyName} onPressEnter={this.handleSearch} />
            </div>
          </Col> */}
          <Button icon='search' onClick={this.handleSearch} />
        </Row>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Fillter)
